package com.njupt.StackAndQueue;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * 20. 有效的括号
 * 括号匹配问题
 */
public class IsValid {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        if (s.length() % 2 != 0) {
            return false;
        }

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
                stack.push(s.charAt(i));
            } else {
                Character rightChar = s.charAt(i);
                if (stack.empty()) {
                    return false;
                }
                Character leftChar = stack.pop();
                if (!isMatch(leftChar, rightChar)) {
                    return false;
                }
            }
        }
        if (stack.size() == s.length() || !stack.empty()) {
            return false;
        }
        return true;
    }

    private boolean isMatch(Character leftChar, Character rightChar) {

        switch (leftChar) {
            case '{':
                if (rightChar == '}') return true;
                break;
            case '(':
                if (rightChar == ')') return true;
                break;
            case '[':
                if (rightChar == ']') return true;
                break;
            default:
                return false;
        }
        return false;
    }


    /**
     * 如果将左括号压入栈中，遇到右括号弹出栈，那么还要写一个左右括号是否匹配的逻辑，
     * 换一种想法，我们可以遇到左括号是，将其对应的右括号压入栈中
     *
     * @param s
     * @return
     */
    public boolean isValid1(String s) {
        Deque<Character> stack = new LinkedList<Character>();

        for (int i = 0; i < s.length(); i++) {

            if(s.charAt(i) == '('){
                stack.push(')');
            } else if (s.charAt(i) == '[') {
                stack.push(']');
            } else if (s.charAt(i) == '{') {
                stack.push('}');
            } else if (stack.isEmpty() || s.charAt(i) != stack.peek()) {
                return false;
            }else {
                stack.pop();
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        String s = "()";
        IsValid test = new IsValid();
        System.out.println(test.isValid1(s));
    }
}
